$.ajaxSetup({
    async: false
});

// fetch封装
async function request(url, data) {
    let formData = new FormData()
    for (const key in data) {
        if (Object.hasOwnProperty.call(data, key)) {
            const element = data[key];
            formData.append(`${key}`, `${element}`)
        }
    }
    const result = await fetch(`/apis/m/ajax/${url}`, {
            method: 'POST',
            mode: 'cors',
            body: formData
        }).then(res => res.json())
        .then(json => {
            if (json.errno == 505) {
                wx_auth();
            } else {
                return json
            }
        })
    return result
}

let shareInfo //获取分享信息
async function wx_auth() {
    let link = window.location.href;
    let auth_code = getUrlParam('code'); // 地址解析  
    let token = getUrlParam('share_token')
    let type = getUrlParam('item_type')
    console.log(getUrlParam('share_token'));
    if (auth_code) {
        //如果 链接上有code 的话 走 code 换token 流程
        request('user_auth/', {
            code: auth_code
        }).then(res => {
            let json = JSON.stringify(res.rsm)
            localStorage.setItem('userInfo', json);
            localStorage.token = token
            localStorage.type = type
            localStorage.user_token = res.rsm.zm_token;
            request('refresh_settings/', {
                zm_token: localStorage.user_token,
                _zm_post_type: 'ajax'
            }).then(res => {
                let gameStore = res.rsm
                request('refresh_user_score/', {
                    zm_token: localStorage.user_token,
                    _zm_post_type: 'ajax'
                }).then(res => {
                    let userScore = res.rsm
                    //  记得清除
                    // if (localStorage.getItem('game1')) {
                    //     return
                    // } else {
                    let obj1 = {
                        score: userScore.tree_score, //游戏得分
                        active: userScore.tree_score >= gameStore.tree_score, //是否通关
                        luck: gameStore.tree_lottery == 1, //是否抽奖
                        number: 0 //是否是第一次进入游戏
                    }
                    let obj2 = {
                        score: userScore.jump_score, //游戏得分
                        active: userScore.jump_score >= gameStore.jump_score, //是否通关
                        luck: gameStore.tree_lottery == 1, //是否抽奖
                        number: 0 //是否是第一次进入游戏
                    }
                    let obj3 = {
                        score: userScore.dance_score, //游戏得分
                        active: userScore.dance_score >= gameStore.dance_score, //是否通关
                        luck: gameStore.dance_lottery == 1, //是否抽奖
                        number: 0 //是否是第一次进入游戏
                    }
                    obj1 = JSON.stringify(obj1)
                    obj2 = JSON.stringify(obj2)
                    obj3 = JSON.stringify(obj3)
                    localStorage.setItem('game1', obj1)
                    localStorage.setItem('game2', obj2)
                    localStorage.setItem('game3', obj3)
                    localStorage.setItem('gift', gameStore.top_lottery == 1)
                    location.progress = 1
                    // }
                    if (token) {
                        request('share_help/', {
                            zm_token: localStorage.user_token,
                            _zm_post_type: 'ajax',
                            share_token: localStorage.token,
                            item_type: localStorage.type,
                        }).then(() => {
                            localStorage.token = ''
                            localStorage.type = ''
                        })
                    }
                    request('get_share_sign/', {
                        zm_token: localStorage.user_token,
                        _zm_post_type: 'ajax',
                        url: location.href
                    }).then(res => {
                        localStorage.shareInfo = JSON.stringify(res)
                        // console.log(res.rsm);
                        if (res.errno == 505) {
                            let appid = 'wx41fa84947dc4d128';
                            let uri = encodeURIComponent(link);
                            let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
                            window.location.href = authURL;
                        }<p></p>

                    })
                })
            });

        })

    } else {
        //如果链接上没有 code 的话 走授权请求获取code
        let token = getUrlParam('share_token')
        let type = getUrlParam('item_type')
        localStorage.setItem = token
        localStorage.type = type
        localStorage.number = 0
        let appid = 'wx41fa84947dc4d128'; //修改为你的appid
        //1.使用encodeURIComponent以及JSON.stringify()方法对对象进行字符串化和编码，这样可以控制url参数的长度，参考示例代码（uni-app书写方式，微信小程序自己改。）  
        let uri = encodeURIComponent(link);
        //2.接受信息的页面使用JSON.parse()以及decodeURIComponent()接收和解码参数。    
        //snsapi_base   //snsapi_base    scope = snsapi_base（不弹出授权页面，直接跳转，只能获取用户 openid ）。  
        //snsapi_userinfo  弹出  
        let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
        window.location.href = authURL;
    }

}

function getUrlParam(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    let url = window.location.href.split('#')[0]
    let search = url.split('?')[1]
    if (search) {
        var r = search.substr(0).match(reg)
        if (r !== null) return unescape(r[2])
        return null
    } else {
        return null
    }
}

(function (global, undefined) {
    global.locMemory = {};
    global.locMemory.localStorage = {
        setItem: function (key, value, cb) {
            value = JSON.stringify(value);
            value = value || '';
            localStorage.setItem(`${key}`, `${value}`);
            cb && cb();
            return value;
        },
        getItem: function (key, cb) {
            value = localStorage.getItem(key) || '';
            value = value == '' ? '' : JSON.parse(value);
            cb && cb(null, value);
            return value;
        },
        removeItem: function (key, cb) {
            localStorage.removeItem(key);
            cb && cb();
        },
        clear: function (cb) {
            localStorage.clear();
            cb && cb();
        }
    }
}(window))

//隐藏分享按钮
function hideShareBtn(hide = true) {
    let shareInfo = JSON.parse(localStorage.shareInfo)
    console.log(shareInfo);
    request('get_share_sign/', {
        zm_token: localStorage.user_token,
        _zm_post_type: 'ajax',
        url: location.href
    }).then(res => {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: shareInfo.rsm.appId, // 必填，公众号的唯一标识
            timestamp: shareInfo.rsm.timestamp, // 必填，生成签名的时间戳
            nonceStr: shareInfo.rsm.nonceStr, // 必填，生成签名的随机串
            signature: shareInfo.rsm.signature, // 必填，签名
            jsApiList: ['onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
                'onMenuShareTimeline',
                'updateAppMessageShareData',
                'hideOptionMenu',
                'showOptionMenu',
                'hideMenuItems',
                'showMenuItems',
                'hideAllNonBaseMenuItem',
                'showAllNonBaseMenuItem',
            ] // 必填，需要使用的JS接口列表
        });
        wx.ready(function () { //需在用户可能点击分享按钮前就先调用
            if (hide) {
                wx.hideAllNonBaseMenuItem();
            } else {
                wx.updateAppMessageShareData({
                    title: '2021少数民族传统体育竞技', // 分享标题
                    desc: '邀你一起参与游戏，赢取现金红包！', // 分享描述
                    link: `http://youxi.haiqikj.com`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://youxi.haiqikj.com/img/share_img_bg.png', // 分享图标
                    success: function () {
                        console.log('分享成功');
                    }
                })
            }
        });
    })
}